import pandas as pd
import chardet
import hashlib
import re
from collections import defaultdict

def extract_iic_data(file_path, mode='standard'):
    """
    提取IIC数据的核心逻辑
    """
    def detect_file_encoding(file_path):
        """
        自动检测文件编码
        """
        try:
            with open(file_path, 'rb') as f:
                rawdata = f.read(20000)
                result = chardet.detect(rawdata)
                return result['encoding'] or 'utf-8'
        except Exception as e:
            print(f"编码检测失败: {str(e)}")
            return 'utf-8'

    def safe_read_csv(file_path):
        """
        安全读取CSV文件
        """
        encodings = [
            detect_file_encoding(file_path),
            'utf-8-sig',
            'gb18030',
            'latin-1',
            'utf-8'
        ]

        for encoding in encodings:
            try:
                df = pd.read_csv(file_path, encoding=encoding, engine='python', on_bad_lines='warn')
                return df
            except Exception as e:
                print(f"尝试编码 {encoding} 失败: {str(e)}")
        return None

    def clean_hex_value(value):
        """
        清洗并验证十六进制值
        """
        try:
            cleaned = str(value).strip().upper().replace('0X', '')
            if not cleaned:
                return None
            int(cleaned, 16)
            return f"{cleaned.zfill(2)}"
        except:
            return None

    def find_previous_wr(df, start_index):
        """
        向前查找最近的WR记录
        """
        for j in range(start_index - 1, max(-1, start_index - 50), -1):
            current_addr = df.iloc[j]['Address(7b)']
            if 'WR' in current_addr:
                return j
        return None

    def process_iic_records(df):
        """
        处理IIC记录
        """
        results = {}
        content_registry = {}
        name_counters = defaultdict(int)

        i = 0
        while i < len(df):
            current_row = df.iloc[i]
            addr = current_row['Address(7b)']
            if 'RD' in addr:
                wr_index = find_previous_wr(df, i)
                if wr_index is not None:
                    wr_d0 = clean_hex_value(df.iloc[wr_index]['D0'])
                    base_name = f"Reg_{wr_d0}" if wr_d0 else None
                else:
                    rd_d0 = clean_hex_value(current_row.get('D0', ''))
                    rd_d1 = clean_hex_value(current_row.get('D1', ''))
                    base_name = f"Reg_{rd_d0}_{rd_d1}" if rd_d0 and rd_d1 else None

                if not base_name:
                    i += 1
                    continue

                data_block = []
                current_index = i
                data_valid = True

                while data_valid and current_index < len(df):
                    if current_index != i and ('WR' in df.iloc[current_index]['Address(7b)']
                                               or 'RD' in df.iloc[current_index]['Address(7b)']):
                        break

                    row_data = []
                    for k in range(8):
                        val = clean_hex_value(df.iloc[current_index].get(f'D{k}', ''))
                        if val:
                            row_data.append(val.upper())
                        else:
                            if row_data:
                                data_block.extend(row_data)
                            data_valid = False
                            break

                    if data_valid:
                        if row_data:
                            data_block.extend(row_data)
                        current_index += 1
                    else:
                        current_index += 1
                        break

                content_hash = hashlib.md5(str(data_block).encode()).hexdigest()
                if content_hash not in content_registry:
                    name_counters[base_name] += 1
                    final_name = f"{base_name}_{name_counters[base_name]}" if name_counters[base_name] > 1 else base_name
                    content_registry[content_hash] = final_name
                    results[final_name] = data_block

                i = current_index
            else:
                i += 1

        return results

    df = safe_read_csv(file_path)
    if df is None:
        print("无法读取CSV文件")
        return

    results = process_iic_records(df)
    for reg_name, data in results.items():
        print(f"{reg_name}: {data}")